# @Time  :2021/5/27 21:27
# @Author: Houtaroy
from functools import wraps

from flask_jwt_extended import verify_jwt_in_request, get_jwt

from flask_koala.core.exceptions import BusinessException


def authorization(code: str = None):
    """
    鉴权装饰器
    """

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            try:
                verify_jwt_in_request()
            except Exception:
                raise BusinessException("无访问权限", 403)
            if code is None:
                return fn(*args, **kwargs)
            authorities = get_jwt()['authorities']
            if code not in authorities:
                raise BusinessException("无访问权限", 403)
            return fn(*args, **kwargs)

        return wrapper

    return decorator
